package cn.smbms.service;

import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayOpenAuthTokenAppQueryRequest;
import com.alipay.api.request.AlipayOpenAuthTokenAppRequest;
import com.alipay.api.request.AlipaySystemOauthTokenRequest;
import com.alipay.api.request.AlipayUserInfoShareRequest;
import com.alipay.api.response.AlipayOpenAuthTokenAppQueryResponse;
import com.alipay.api.response.AlipayOpenAuthTokenAppResponse;
import com.alipay.api.response.AlipaySystemOauthTokenResponse;
import com.alipay.api.response.AlipayUserInfoShareResponse;

import cn.smbms.config.AlioauthConfig;
import cn.smbms.pojo.AlipayUser;
import lombok.extern.log4j.Log4j;

@Log4j
@Component
public class AlioauthService implements InitializingBean {

	@Autowired
	private AlioauthConfig alioauthConfig;

	private AlipayClient alipayClient;
	
	@Override
	public void afterPropertiesSet() throws Exception {
		alipayClient = new DefaultAlipayClient(alioauthConfig.getUrl(), alioauthConfig.getAppID(),
				alioauthConfig.getRsaPrivateKey(), alioauthConfig.getFormat(), alioauthConfig.getCharset(),
				alioauthConfig.getAlipayPublicKey(), alioauthConfig.getSignType());
	}
	
    /**
     * 访问令牌。通过该令牌调用需要授权类接口
     * 根据 app_auth_code 获取用户的 token
     * @param app_auth_code
     * @return
     * @throws AlipayApiException 
     */
	public String getAccessToken(String auth_code) throws AlipayApiException {
	    // 请求对象
	    AlipaySystemOauthTokenRequest request = new AlipaySystemOauthTokenRequest();
	    // 第一步获取到的：auth_code
	    request.setCode(auth_code);
	    // 授权类型
	    request.setGrantType("authorization_code");
	    // 发起请求
	    AlipaySystemOauthTokenResponse oauthTokenResponse = alipayClient.execute(request);
	    return oauthTokenResponse.getAccessToken();
	}
	
    /**
	* 根据 token 获取用户信息
     * @param token
     * @return
     */
    public AlipayUser getUserInfo(String token) {
        AlipayUserInfoShareRequest request = new AlipayUserInfoShareRequest();
        try {
            AlipayUserInfoShareResponse response =  alipayClient.execute(request, token);
            System.out.println(response.getBody());
            if (response.isSuccess()) {
                //封装支付宝对象信息
                AlipayUser alipayUser = new AlipayUser();
                alipayUser.setUserId(response.getUserId());
                alipayUser.setAddress(response.getAddress());
                alipayUser.setCertNo(response.getCertNo());
                alipayUser.setCity(response.getCity());
                alipayUser.setCollegeName(response.getCollegeName());
                alipayUser.setDegree(response.getDegree());
                alipayUser.setMobile(response.getMobile());
                alipayUser.setPhone(response.getPhone());
                alipayUser.setProvince(response.getProvince());
                alipayUser.setUserName(response.getUserName());
                alipayUser.setNickName(response.getNickName());
                return alipayUser;
            }
            log.error("根据  token 获取用户信息失败!");
            return null;
        } catch (Exception e) {
            log.error("根据 token 获取用户信息抛出异常！", e);
            return null;
        }
    }
	
    /**
     * 应用授权令牌
     * 根据 app_auth_code 获取用户的 token
     * @param app_auth_code
     * @return
     * @throws AlipayApiException 
     */	
    public String getAppAuthToken(String app_auth_code) throws AlipayApiException {
		// 通过 app_auth_code 获得 token
		AlipayOpenAuthTokenAppRequest oauthRequest = new AlipayOpenAuthTokenAppRequest();
		oauthRequest.setBizContent(
				"{" + "\"grant_type\":\"authorization_code\"," + "\"code\":\"" + app_auth_code + "\"" + "}");
		// 第三方授权信息
		AlipayOpenAuthTokenAppResponse responseToken = alipayClient.execute(oauthRequest);
		return responseToken.getAppAuthToken();
    }
    /**
     * 通过应用授权令牌查询授权信息
     * @param token
     * @return
     */
    public String getAuthInfo(String token) {
		// 
		AlipayOpenAuthTokenAppQueryRequest oauthRequest = new AlipayOpenAuthTokenAppQueryRequest();
		oauthRequest.setBizContent("{" + "    \"app_auth_token\":\"" + token + "\"" + "  }");
		try {
			AlipayOpenAuthTokenAppQueryResponse responseToken = alipayClient.execute(oauthRequest);
			return responseToken.getUserId();
		} catch (AlipayApiException e) {
			// 处理异常
			e.printStackTrace();
			return null;
		}        
    }
    
}
